﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace antyspam_filter
{
    public class EmailHeader
    {
        private List<EmailServer> _servers;
        private string _from;
        private string _to;
        private string _subject;

        public List<EmailServer> Servers
        {
            get
            {
                return this._servers;
            }
        }
        public string EmailFrom
        {
            get
            {
                return this._from;
            }
        }
        public string EmailTo
        {
            get
            {
                return this._to;
            }
        }
        public string EmailSubject
        {
            get
            {
                return this._subject;
            }
        }

        public EmailHeader(string text)
        {
            this._servers = new List<EmailServer>();

            string[] lines = text.Split('\n');
            foreach (string line in lines)
            {
                if (Regex.IsMatch(line, "^Received:"))
                {
                    string[] temp = line.Split(' ');
                    if (temp[1].Equals("from"))
                    {
                        this._servers.Add(new EmailServer(temp[2], Regex.Match(temp[temp.Length - 1], @"\b(?:\d{1,3}\.){3}\d{1,3}\b").Value));
                    }
                }
                else if (Regex.IsMatch(line, "^From:"))
                {
                    this._from = line.Replace("From:", "").Replace("<", "").Replace(">", "").Replace("\r", "");
                }
                else if (Regex.IsMatch(line, "^To:"))
                {
                    this._to = line.Replace("To:", "").Replace("<", "").Replace(">", "").Replace("\r", "");
                }
                else if (Regex.IsMatch(line, "^Subject:"))
                {
                    this._subject = line.Substring(9);
                }
            }
        }

        public override string ToString()
        {
            StringBuilder returnString = new StringBuilder();

            foreach (EmailServer server in _servers)
            {
                returnString.Append("Server: " +server.ToString() + "\r\n"); 
            }
            returnString.Append("From: " + this._from + "\r\n");
            returnString.Append("To: " + this._to + "\r\n");
            returnString.Append("Subject: " + this._subject + "\r\n");
            return returnString.ToString();
        } 
    }
}
